/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.terramagnet.mvcframework.resource;

import org.terramagnet.mvcframework.tools.Hex62Util;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;
import org.springframework.util.DigestUtils;

public class ResourceArchive {

    public static final ResourceArchive EMPTY = new ResourceArchive(null, null);

    private static final Pattern image = Pattern.compile(".*\\.(png|jpe?g|gif)$");

    private final File file;
    private final String url;
    private String hash;
    private String key;

    private Long id;

    public ResourceArchive(File file, String url) {
        this.file = file;
        this.url = url;
    }

    public File getFile() {
        return file;
    }

    public String getUrl() {
        return url;
    }

    /**
     * 确实是本地资源. 尽管资源文件可能不存在。
     */
    public boolean isLocalResource() {
        return file != null;
    }

    /**
     * 资源文件存在于本地.
     */
    public boolean exists() {
        return file != null && file.exists();
    }

    public String getHash() {
        if (hash == null) {
            if (url == null) {
                throw new IllegalStateException("Empty Resource has no key!");
            }
            try {
                hash = DigestUtils.md5DigestAsHex(url.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException ex) {// this will not happen!
                throw new RuntimeException("UnsupportedEncoding:UTF-8", ex);
            }
        }
        return hash;
    }

    /**
     * 返回资源的hex值. 资源{@link #getId() id}的62进制
     *
     * @return
     */
    public String getHex() {
        if (id == null) {
            return null;
        }
        return Hex62Util.toString(id, 62);
    }

    public boolean isImage() {
        return image.matcher(file.getName()).matches();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}
